package com.zs.blog.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zs.blog.dao.IRoleAuthorityMapper;
import com.zs.blog.model.dto.GrantedDTO;
import com.zs.blog.model.entity.RoleAuthority;
import com.zs.blog.service.IRoleAuthorityService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * @Title: IRoleAuthorityServiceImpl
 * @Author zs
 * @Package com.zs.blog.service.impl
 * @Date 2025/9/8 21:44
 * @description: 角色-权限服务层接口实现类
 */
@Service
public class IRoleAuthorityServiceImpl extends ServiceImpl<IRoleAuthorityMapper, RoleAuthority> implements IRoleAuthorityService {

    public IRoleAuthorityMapper roleAuthorityMapper;

    @Autowired
    public IRoleAuthorityServiceImpl(IRoleAuthorityMapper roleAuthorityMapper) {
        this.roleAuthorityMapper = roleAuthorityMapper;
    }

    /**
     * 授予角色菜单或系统资源权限的数据转换对象
     *
     * @param grantedDTO 收集授予角色菜单或系统资源权限的参数对象
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void insertOrDeleteRoleAuthority(GrantedDTO grantedDTO) {
        // 查询出角色ID对应的权限
        if (grantedDTO.getRoleId() != null) {
            LambdaQueryWrapper<RoleAuthority> lqw = new LambdaQueryWrapper<>();
            lqw.eq(RoleAuthority::getRoleId, grantedDTO.getRoleId());
            List<RoleAuthority> roleAuthorities = roleAuthorityMapper.selectList(lqw);

            /*
             * 旧的数据 新的数据
             * 新的数据包含了旧的数据ID 找出不重复的ID-->插入
             * 新的数据不包含旧的数据ID 新的插入 旧的删除
             * 新的数据与旧的数据有一些重合 重合的不做改变 新的不重复的插入 旧的不重复删除0
             * newDataDifferenceSet oldDataDifferenceSet
             */
            List<Long> oldDataList = new ArrayList<>();
            if (roleAuthorities != null) {
                roleAuthorities.forEach(item -> {
                    oldDataList.add(item.getAuthorityId());
                });
            }

            Set<Long> newDataSet = new HashSet<>(Optional.ofNullable(grantedDTO.getSysResourceIds()).orElse(Collections.emptyList()));
            Set<Long> oldDataSet = new HashSet<>(oldDataList);
            Set<Long> newDataDifferenceSet = Stream.concat(newDataSet.stream(), oldDataSet.stream())
                    .filter(e -> !oldDataSet.contains(e))
                    .collect(Collectors.toSet());
            Set<Long> oldDataDifferenceSet = Stream.concat(newDataSet.stream(), oldDataSet.stream())
                    .filter(e -> !newDataSet.contains(e))
                    .collect(Collectors.toSet());
            // 删除旧的数据
            if (!oldDataDifferenceSet.isEmpty()) {
                LambdaQueryWrapper<RoleAuthority> deleteLqw = new LambdaQueryWrapper<>();
                deleteLqw.eq(RoleAuthority::getRoleId, grantedDTO.getRoleId())
                        .in(RoleAuthority::getAuthorityId, oldDataDifferenceSet);
                roleAuthorityMapper.delete(deleteLqw);
            }
            // 插入新的数据
            if (!newDataDifferenceSet.isEmpty()) {
                // 将要保存的数据
                List<RoleAuthority> insertEntityList = new ArrayList<>();

                // 构造实体类
                Long[] array = newDataDifferenceSet.toArray(new Long[0]);
                Arrays.stream(array).toList().forEach(item -> {
                    RoleAuthority roleAuthority = new RoleAuthority();
                    roleAuthority.setRoleId(grantedDTO.getRoleId());
                    roleAuthority.setAuthorityId(item);
                    insertEntityList.add(roleAuthority);
                });

                // 插入数据
                roleAuthorityMapper.insert(insertEntityList);
            }

        }
    }
}
